<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
   <HEAD>
      <TITLE>
         Integrating FastCGI with Java
      </TITLE>
<STYLE TYPE="text/css">
 body {
  background-color: #FFFFFF;
  color: #000000;
 }
 :link { color: #cc0000 }
 :visited { color: #555555 }
 :active { color: #000011 }
 dt.c4 {font-style: italic}
 h5.c3 {text-align: center}
 p.c2 {text-align: center}
 div.c1 {text-align: center}
</STYLE>
   </HEAD>
   <BODY>
      <DIV CLASS="c1">
         <A HREF="http://fastcgi.com"><IMG BORDER="0" SRC="../images/fcgi-hd.gif" ALT="[[FastCGI]]"></A>
      </DIV>
      <BR CLEAR="all">
      <DIV CLASS="c1">
         <H3>
            Integrating FastCGI with Java
         </H3>
      </DIV>
      <!--Copyright (c) 1996 Open Market, Inc.                                    -->
      <!--See the file "LICENSE.TERMS" for information on usage and redistribution-->
      <!--of this file, and for a DISCLAIMER OF ALL WARRANTIES.                   -->
      <!-- $Id: fcgi-java.htm,v 1.4 2002/02/25 00:42:59 robs Exp $ -->
      <P CLASS="c2">
         Steve Harris<BR>
         Open Market, Inc.<BR>
         <EM>7 May 1996</EM>
      </P>
      <H5 CLASS="c3">
         Copyright &copy; 1996 Open Market, Inc. 245 First Street, Cambridge, MA 02142 U.S.A.<BR>
         Tel: 617-621-9500 Fax: 617-621-1703 URL: <A HREF=
         "http://www.openmarket.com/">http://www.openmarket.com/</A><BR>
      </H5>
      <HR>
      <H3>
         <A NAME="S1">1. Introduction</A>
      </H3>
      <P>
         Java is an object-oriented programming language developed by Sun Microsystems. The Java Depvelopers Kit (JDK),
         which contains the basic Java class packages, is available from Sun in both source and binary forms at
         Sun&#39;s <A HREF="http://java.sun.com/java.sun.com/JDK-1.0/index.html">JavaSoft</A> site. This document
         assumes that you have some familiarity with the basics of compiling and running Java programs.
      </P>
      <P>
         There are two kinds of applications built using Java.
      </P>
      <UL>
         <LI>
            <I>Java Applets</I> are graphical components which are run off HTML pages via the <TT>&lt;APPLET&gt;</TT>
            HTML extention tag.<BR>
            <BR>
         </LI>
         <LI>
            <I>Java Applications (Apps)</I> are stand-alone programs that are run by invoking the Java interpreter
            directly. Like C programs, they have a <TT>main()</TT> method which the interpreter uses as an entry point.
         </LI>
      </UL>
      <P>
         The initial emphasis on using Java for client side applets should not obscure the fact that Java is a full
         strength programming language which can be used to develop server side stand alone applications, including CGI
         and now FastCGI applications.
      </P>
      <P>
         The remainder of this document explains how to write and run FastCGI Java applications. It also illustrates
         the conversion of a sample Java CGI program to a FastCGI program.
      </P>
      <H3>
         <A NAME="S2">2. Writing FastCGI applications in Java</A>
      </H3>
      <P>
         Writing a FastCGI application in Java is as simple as writing one in C.
      </P>
      <OL>
         <LI>
            Import the <TT>FCGIInterface</TT> class.
         </LI>
         <LI>
            Perform one-time initialization at the top of the <TT>main()</TT> method.
         </LI>
         <LI>
            Create a new <TT>FCGIInterface</TT> object and send it an <TT>FCGIaccept()</TT> message in a loop.
         </LI>
         <LI>
            Put the per-request application code inside that loop.
         </LI>
      </OL>
      <P>
         On return from <TT>FCGIaccept()</TT> you can access the request&#39;s environment variables using
         <TT>System.getProperty</TT> and perform request-related I/O through the standard variables <TT>System.in</TT>,
         <TT>System.out</TT>, and <TT>System.err</TT>.
      </P>
      <P>
         To illustrate these points, the kit includes <TT>examples/TinyCGI</TT>, a CGI Java application, and
         <TT>examples/TinyFCGI</TT>, the FastCGI version of TinyCGI. These programs perform the same functions as the C
         programs <TT>examples/tiny-cgi.c</TT> and <TT>examples/tiny-fcgi.c</TT> that are used as examples in the <A
         HREF="fcgi-devel-kit.htm#S3.1.1">FastCGI Developer&#39;s Kit document</A>.
      </P>
      <H4>
         A. TinyCGI
      </H4>
<PRE>
 
class TinyCGI { 
 public static void main (String args[]) {  
  int count = 0;
                ++count;
  System.out.println(&quot;Content-type: text/html\n\n&quot;);
  System.out.println(&quot;&lt;html&gt;&quot;);
  System.out.println(
                 &quot;&lt;head&gt;&lt;TITLE&gt;CGI Hello&lt;/TITLE&gt;&lt;/head&gt;&quot;);
  System.out.println(&quot;&lt;body&gt;&quot;);
  System.out.println(&quot;&lt;H3&gt;CGI-Hello&lt;/H3&gt;&quot;);
  System.out.println(&quot;request number &quot; + count + 
     &quot; running on host &quot; 
    + System.getProperty&lt;&quot;SERVER_NAME&quot;));
  System.out.println(&quot;&lt;/body&gt;&quot;);
  System.out.println(&quot;&lt;/html&gt;&quot;); 
  }
 }

</PRE>
      <H4>
         B. TinyFCGI
      </H4>
<PRE>
 
import FCGIInterface;

class TinyFCGI { 
 public static void main (String args[]) {  
  int count = 0;
   while(new FCGIInterface().FCGIaccept()&gt;= 0) {
   count ++;
   System.out.println(&quot;Content-type: text/html\n\n&quot;);
   System.out.println(&quot;&lt;html&gt;&quot;);
   System.out.println(
     &quot;&lt;head&gt;&lt;TITLE&gt;FastCGI-Hello Java stdio&lt;/TITLE&gt;&lt;/head&gt;&quot;);
   System.out.println(&quot;&lt;body&gt;&quot;);
   System.out.println(&quot;&lt;H3&gt;FastCGI-HelloJava stdio&lt;/H3&gt;&quot;);
   System.out.println(&quot;request number &quot; + count + 
     &quot; running on host &quot; 
    + System.getProperty&lt;&quot;SERVER_NAME&quot;));
   System.out.println(&quot;&lt;/body&gt;&quot;);
   System.out.println(&quot;&lt;/html&gt;&quot;); 
   }
  }
 }

</PRE>
      <H4>
         C. Running these Examples
      </H4>
      <P>
         We assume that you have downloaded the JDK and the FastCGI Developer&#39;s Kit, and that you have a Web server
         running that can access the <TT>fcgi-devel-kit/examples</TT> directory. In all cases where we specify paths,
         we are using relative paths within <TT>fcgi-devel-kit</TT> or the JDK which will need to be enlarged to a full
         path by the user.
      </P>
      <H5>
         Configuring
      </H5>
      <OL>
         <LI>
            Add your JDK&#39;s <TT>java/bin</TT> directory to your Unix <TT>PATH</TT> if it isn&#39;t there
            already.<BR>
            <BR>
         </LI>
         <LI>
            Add the directories <TT>fcgi-devel-kit/examples</TT> and <TT>fcgi-devel-kit/java/classes</TT> to your Java
            <TT>CLASSPATH</TT>.<BR>
            <BR>
         </LI>
         <LI>
            In your Open Market Secure WebServer configuration file, <TT>httpd.config</TT>, add the following two
            lines:<BR>
            <BR>
             <TT>ExternalAppClass TinyFCGI -host</TT> <I>hostName:portNum</I><BR>
             <TT>Responder TinyFCGI fcgi-devel-kit/examples/TinyFCGI</TT><BR>
            <BR>
             
            <UL>
               <LI>
                  <I>hostName</I> is the name of your host machine.<BR>
               </LI>
               <LI>
                  <I>portNum</I> is the port that you&#39;ve selected for communication between the Web server and the
                  Java application.<BR>
               </LI>
            </UL>
            <BR>
             On other servers you can use <TT>cgi-fcgi</TT> to get a similar effect.
         </LI>
         <LI>
            Create a soft link <TT>examples/javexe</TT> to the <TT>java/bin</TT> directory in your JDK. This link is
            required only to run the CGI scripts <TT>examples/TinyCGI.cgi</TT> and <TT>examples/TinyFCGI.cgi</TT>,
            which use it to invoke the Java interpreter <TT>java/bin/java</TT>. It is not used by FastCGI applications.
         </LI>
         <LI>
            You might have to modify <TT>examples/TinyFCGI.cgi</TT> to use a Unix shell for which your CLASSPATH is
            defined.
         </LI>
      </OL>
      <H5>
         Running
      </H5>
      <UL>
         <LI>
            To run TinyFCGI as FastCGI, you invoke the Java interpreter with the -D option, giving it the
            <TT>FCGI_PORT</TT> environment variable and the same <I>portNum</I> that was used in the Web server
            configuration. The command is:<BR>
            <BR>
             <TT>java -DFCGI_PORT=portNum TinyFCGI</TT><BR>
            <BR>
             Then point your browser at <TT>fcgi-devel-kit/examples/TinyFCGI</TT>. Notice that each time you reload,
            the count increments.<BR>
            <BR>
         </LI>
         <LI>
            To run TinyCGI, point your browser at <TT>fcgi-devel-kit/examples/TinyCGI.cgi</TT> on your host machine.
            Notice that the count does not increment.<BR>
            <BR>
         </LI>
         <LI>
            Finally, you can run TinyFCGI as a straight CGI program by pointing your browser at
            <TT>fcgi-devel-kit/examplesi/TinyFCGI.cgi.</TT> The results are exactly the same as when you ran TinyCGI.
            Invoking a FastCGI program without an <TT>FCGI_PORT</TT> parameter tells the FastCGI interface to leave the
            normal CGI environment in place.
         </LI>
      </UL>
      <P>
         Due to gaps in the Java interpreter&#39;s support for listening sockets, Java FastCGI applications are
         currently limited to being started as external applications. They can&#39;t be started and managed by the Web
         server because they are incapable of using a listening socket that the Web server creates.
      </P>
      <H3>
         <A NAME="S3">3. Standard I/O and Application Libraries</A>
      </H3>
      <P>
         As we have seen above, FastCGI for Java offers a redefinition of standard I/O corresponding to the the
         <I>fcgi_stdio</I> functionality. It also offers a set of directly callable I/O methods corresponding to the
         <I>fcgiapp</I> C library. To understand where these methods occur we need to look briefly at the FastCGI
         redefinition of standard I/O.
      </P>
      <P>
         Java defines standard I/O in the <I>java.System</I> class as follows:
      </P>
      <P>
         public static InputStream in = new BufferedInputStream(new FileInputStream(FileDescriptor.in), 128);<BR>
         public static PrintStream out = new PrintStream(new BufferedOutputStream(new
         FileOutputStream(FileDescriptor.out), 128), true);<BR>
         public static PrintStream err = new PrintStream(new BufferedOutputStream(new
         FileOutputStream(FileDescriptor.err), 128), true);
      </P>
      <P>
         The File Descriptors <I>in</I>, <I>out</I>, <I>err</I> are constants set to 0, 1 and 2 respectively.
      </P>
      <P>
         The FastCGI interface redefines <I>java.System in, out</I>, and <I>err</I> by replacing the File streams with
         Socket streams and inserting streams which know how to manage the FastCGI protocol between the Socket streams
         and the Buffered streams in the above definitions.
      </P>
      <P>
         For those cases where the FCGI application needs to bypass the standard I/O streams, it can directly access
         the methods of the FCGI input and output streams which roughly correspond to the functions in the C
         <I>fcgiapp</I> library. These streams can be accessed via the <I>request</I> class variable in FCGIInterface.
         Each Request object has instance variables that refer to an FCGIInputStream, and to two FCGIOutputStreams
         associated with that request.
      </P>
      <H3>
         <A NAME="S4">4. Environment Variables</A>
      </H3>
      <P>
         Java does not use the C <I>environ</I> list. Nor is there a <I>getenv</I> command that reads system
         environment variables. This is intentional for reasons of portability and security. Java has an internal
         dictionary of properties which belongs to the System class. These System properties are <I>name/value</I>
         associations that constitute the Java environment. When a Java application starts up, it reads in a file with
         default properties. As we have seen, additional System properties may be inserted by using the -D <I>Java</I>
         command argument.
      </P>
      <P>
         For CGI, where the Java application is invoked from a .cgi script that, in turn, invokes the Java interpreter,
         this script could read the environment and pass the variables to the Java application either by writing a file
         or by creating -D options on the fly. Both of these methods are somewhat awkward.
      </P>
      <P>
         For FastCGI Java applications, the environment variables are obtained from the FastCGI web server via
         <TT>FCGI_PARAMS</TT> records that are sent to the application at the start of each request. The FastCGI
         interface stores the original startup properties, combines these with the properties obtained from the server,
         and puts the new set of properties in the System properties dictionary. The only parameter that has to be
         specifically added at startup time is the FCGI_PORT parameter for the Socket creation. In the future, we
         expect that even this parameter won&#39;t be needed, since its use is due to an acknowledged rigidity in the
         JDK&#39;s implementation of sockets.
      </P>
      <P>
      </P>
      <H3>
         <A NAME="S4">5. Further examples: EchoFCGI and Echo2FCGI</A>
      </H3>
      <P>
         The next two examples illustrate the points made in the last two sections. EchoFCGI and Echo2FCGI both echo
         user input and display the application&#39;s environment variables. EchoFCGI reads the user input from
         System.in, while Echo2FCGI reads the user input directly from the intermediate FastCGI input stream.
      </P>
      <H4>
         A. EchoFCGI
      </H4>
<PRE>
import FCGIInterface;
import FCGIGlobalDefs;
import java.io.*;

class EchoFCGI {
 
 public static void main (String args[]) {
  int status = 0;
   while(new FCGIInterface().FCGIaccept()&gt;= 0) {
  System.out.println(&quot;Content-type: text/html\n\n&quot;);
   System.out.println(&quot;&lt;html&gt;&quot;);
   System.out.println(
    &quot;&lt;head%gt;&lt;TITLE&gt;FastCGI echo
                                      &lt;/TITLE&gt;&lt;/head&gt;&quot;);
   System.out.println(&quot;&lt;body&gt;&quot;); 
   System.out.println(
                                         &quot;&lt;H2&gt;FastCGI echo&lt;/H2&gt;&quot;);
   System.out.println(&quot;&lt;H3&gt;STDIN&lt;/H3&gt;&quot;);
   for ( int c = 0; c != -1; ) {
    try {
     c = System.in.read();
    } catch(IOException e) {
     System.out.println(
     &quot;&lt;br&gt;&lt;b&gt;SYSTEM EXCEPTION&quot;);
     Runtime rt = Runtime.getRuntime();
     rt.exit(status);
     }
    if (c != -1) { 
     System.out.print((char)c);
     }
    }
   System.out.println(
    &quot;&lt;H3&gt;Environment Variables:&lt;/H3&gt;&quot;);
 
   System.getProperties().list(System.out);
   System.out.println(&quot;&lt;/body&gt;&quot;);
   System.out.println(&quot;&lt;/html&gt;&quot;);
      }
  }
   }
</PRE>
      <H4>
         B. Echo2FCGI
      </H4>
<PRE>
import FCGIInterface;
import FCGIGlobalDefs;
import FCGIInputStream;
import FCGIOutputStream;
import FCGIMessage;
import FCGIRequest;
import java.io.*;

class Echo2FCGI {

 public static void main (String args[]) {
  int status = 0;
                FCGIInterface intf = new FCGIInterface();
   while(intf.FCGIaccept()&gt;= 0) {
  System.out.println(&quot;Content-type: text/html\n\n&quot;);
   System.out.println(&quot;&lt;html&gt;&quot;);
   System.out.println(
    &quot;&lt;head&gt;&lt;TITLE&gt;FastCGI echo
                                    &lt;/TITLE&gt;&lt;/head&gt;&quot;);
   System.out.println(&quot;&lt;body&gt;&quot;);   
   System.out.println(&quot;&lt;H2&gt;FastCGI echo&lt;/H2&gt;&quot;);
   System.out.println(&quot;&lt;H3&gt;STDIN:&lt;/H3&quot;&gt;);
   for ( int c = 0; c != -1; ) {
    try {
     c = intf.request.inStream.read();
    } catch(IOException e) {
     System.out.println(
     &quot;&lt;br&gt;&lt;b&gt;SYSTEM EXCEPTION&quot;);
     Runtime rt = Runtime.getRuntime();
     rt.exit(status);
     }
    if (c != -1) { 
     System.out.print((char)c);
     }
    }
   System.out.println(
    &quot;&lt;H3&gt;Environment Variables:&lt;/H3&gt;&quot;);
 
   System.getProperties().list(System.out);
   System.out.println(&lt;&quot;/body&gt;&quot;);
   System.out.println(&quot;&lt;/html&gt;&quot;);
      }
  }
   }
</PRE>
      <H4>
         C. Running these Examples
      </H4>
      <H5>
         Configuring
      </H5>
      <P>
         As with TinyFCGI, you need to configure the web server to recognize these two FastCGI applications. Your
         configuration now looks like this:
      </P>
      <P>
      </P>
<PRE>
ExternalAppClass java1 -host hostname:portNum
Responder java1 fcgi-devel-kit/examples/TinyFCGI
ExternalAppClass java2 -host hostname:portNumA
Responder java2 fcgi-devel-kit/examples/EchoFCGI
ExternalAppClass java3 -host hostname:porNumB
Responder java3 fcgi-devel-kit/examples/Echo2FCGI
</PRE>
      <P>
         Note that the application classes and port numbers are different for each application.
      </P>
      <H5>
         Running
      </H5>
      <P>
         As with TinyFCGI, you need to run these programs with the -D option using FCGI_PORT and the appropriate port
         number. To get some data for standard input we have created two html pages with forms that use a POST method.
         These are echo.html and echo2.html. You must edit these .html files to expand the path to
         <I>fcgi-devel-kit/examples</I> to a full path. Once the appropriate Java program is running, point your
         browser at the corresponding HTML page, enter some data and select the <I>go_find</I> button.
      </P>
      <H3>
         <A NAME="S6">6. FastCGI Java Classes</A>
      </H3>
      <P>
         The Java FastCGI classes are included in both source and byte code format in <I>fcgi-devel-kit/java/src</I>
         and :<I>fcgi-devel-kit/java/classes</I> respectively. The following is a brief description of these classes:
      </P>
      <P>
      </P>
      <DL>
         <DT CLASS="c4">
            FCGIInterface
         </DT>
         <DD>
            This class contains the FCGIaccept method called by the FastCGI user application. This method sets up the
            appropriate FastCGI environment for communication with the web server and manages FastCGI requests.<BR>
         </DD>
         <DT CLASS="c4">
            FCGIInputStream
         </DT>
         <DD>
            This input stream manages FastCGI internal buffers to ensure that the user gets all of the FastCGI messages
            associated with a request. It uses FCGIMessage objects to interpret these incoming messages.<BR>
         </DD>
         <DT CLASS="c4">
            FCGIOutputStream
         </DT>
         <DD>
            This output stream manages FastCGI internal buffers to send user data back to the web server and to notify
            the server of various FCGI protocol conditions. It uses FCGIMessage objects to format outgoing FastCGI
            messages.<BR>
         </DD>
         <DT CLASS="c4">
            FCGIMessage
         </DT>
         <DD>
            This is the only class that understands the actual structure of the FastCGI messages. It interprets
            incoming FastCGI records and constructs outgoing ones..<BR>
         </DD>
         <DT CLASS="c4">
            FCGIRequest
         </DT>
         <DD>
            This class currently contains data fields used by FastCGI to manage user requests. In a multi-threaded
            version of FastCGI, the role of this class will be expanded.<BR>
         </DD>
         <DT CLASS="c4">
            FCGIGlobalDefs
         </DT>
         <DD>
            This class contains definitions of FastCGI constants.
         </DD>
      </DL>
      <HR>
      <ADDRESS>
         <A HREF="mailto:harris@openmarket.com">Steve Harris // harris@openmarket.com</A>
      </ADDRESS>
   </BODY>
</HTML>

